package com.a01_2021.thousandstimes.instance.service.impl;

import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.exception.CustomExceptionType;
import com.a01_2021.thousandstimes.general.service.SysUserService;
import com.a01_2021.thousandstimes.instance.entity.Communication;
import com.a01_2021.thousandstimes.instance.mapper.CommunicationMapper;
import com.a01_2021.thousandstimes.instance.service.ICommunicationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author E1xP
 * @since 2021-03-30
 */
@Service
public class CommunicationServiceImpl extends ServiceImpl<CommunicationMapper, Communication> implements ICommunicationService {

    @Resource
    CommunicationMapper communicationMapper;

    @Resource
    SysUserService sysUserService;

    /**
     * 发送即时消息
     *
     * @param userId       用户id
     * @param targetUserId 消息目标用户id
     * @param content      消息内容
     * @return Communication沟通消息类
     * @throws CustomException 当不存在消息的目标用户时抛出该异常
     */
    @Override
    public Communication send(long userId, long targetUserId, String content) throws CustomException {
        if (!sysUserService.isUser(targetUserId)) {
            throw new CustomException(CustomExceptionType.USER_NOT_FOUND_ERROR, "找不到该用户");
        }
        Communication communication = new Communication(null, userId, targetUserId, content, LocalDateTime.now());
        communicationMapper.insert(communication);
        return communication;
    }

    /**
     * 获取特定时间之后某用户收到的消息
     *
     * @param userId 用户id
     * @param time   特定时间
     * @return List联系列表
     */
    public List<Communication> receive(long userId, LocalDateTime time) {
        QueryWrapper<Communication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("to_user_id", userId);
        queryWrapper.ge("send_date", time);
        return communicationMapper.selectList(queryWrapper);
    }

    /**
     * 获取给定时间某月中收发的信息数
     *
     * @param userId 用户id
     * @param date   月份时间
     * @return 统计的信息数
     */
    public int getCommunicationCount(long userId, LocalDate date) {
        QueryWrapper<Communication> queryWrapper = new QueryWrapper<>();
        //获取消息发送与接收的数量
        queryWrapper.eq("user_id", userId).or().eq("to_user_id", userId);
        //设定起止时间
        LocalDateTime startTime = LocalDateTime.of(date.getYear(), date.getMonth(), 1, 0, 0, 0);
        date = date.plusMonths(1);
        LocalDateTime endTime = LocalDateTime.of(date.getYear(), date.getMonth(), 1, 0, 0, 0);
        queryWrapper.between("send_date", startTime, endTime);
        return communicationMapper.selectCount(queryWrapper);
    }
}
